<template>
  <div class="app-container">
    <!-- 顶部搜索区域 -->
    <div class="filter-container">
      <div class="search-container">
        <div class="search-item">
          <span class="search-title">公告标题</span>
          <el-input size="small" v-model="title" placeholder="请输入公告标题" style="width: 220px"></el-input>
        </div>
        <div class="search-item">
          <span class="search-title">状态</span>
          <el-select size="small" v-model="status" placeholder="请选择状态" style="width: 120px">
            <el-option label="全部" value=""></el-option>
            <el-option label="发布" :value="1"></el-option>
            <el-option label="下线" :value="3"></el-option>
          </el-select>
        </div>
        <div class="search-item">
          <el-button type="primary" size="small" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        </div>
      </div>
      <div class="right-container">
        <el-button type="primary" plain icon="el-icon-plus" size="small" @click="handleAdd">发布公告</el-button>
      </div>
    </div>

    <!-- 数据区域 -->
    <el-table :data="notices" style="width: 100%;" height="700">
      <el-table-column prop="noticeId" align="center" label="公告ID" width="100"></el-table-column>
      <el-table-column prop="title" align="center" label="公告标题" min-width="200">
        <template slot-scope="scope">
          <div style="display: flex; align-items: center;">
            <el-tag v-if="scope.row.isTop === 1" type="danger" size="mini" style="margin-right: 8px;">置顶</el-tag>
            <span>{{ scope.row.title }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="type" align="center" label="公告类型" width="120">
        <template slot-scope="scope">
          <el-tag :type="scope.row.type === 1 ? 'primary' : (scope.row.type === 2 ? 'success' : 'warning')">
            {{ scope.row.type === 1 ? '系统公告' : (scope.row.type === 2 ? '活动公告' : '维护公告') }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="publisherName" align="center" label="发布人" width="120"></el-table-column>
      <el-table-column label="状态" align="center" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '发布' : '下线' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdTime" label="创建时间" align="center" width="160"></el-table-column>
      <el-table-column prop="updatedTime" label="更新时间" align="center" width="160"></el-table-column>
      <el-table-column label="操作" width="300" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleView(scope.row)">
            <i class="el-icon-view" style="margin-right: -3px;"></i>
            查看
          </el-button>
          <el-button size="mini" type="text" @click="handleEdit(scope.row)">
            <i class="el-icon-edit" style="margin-right: -3px;"></i>
            编辑
          </el-button>
          <el-button
            size="mini"
            type="text"
            style="margin-right: 4px;"
            @click="handleTopChange(scope.row)"
          >
            <i :class="scope.row.isTop === 1 ? 'el-icon-bottom' : 'el-icon-top'" style="margin-right: -3px;"></i>
            {{ scope.row.isTop === 1 ? '取消置顶' : '置顶' }}
          </el-button>
          <el-button
            size="mini"
            type="text"
            style="margin-right: 4px;"
            @click="handleStatusChange(scope.row)"
          >
            <i class="el-icon-refresh" style="margin-right: -3px;"></i>
            状态
          </el-button>
          <el-button
            size="mini"
            type="text"
            style="margin-right: 4px;"
            @click="handleDelete(scope.row)"
          >
            <i class="el-icon-delete" style="margin-right: -3px;"></i>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <el-pagination
      class="pagination-container"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>

    <!-- 添加/编辑公告对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="800px"
      :before-close="handleClose"
    >
      <el-form
        :model="formData"
        class="addDialog"
        :rules="rules"
        ref="formRef"
        size="small"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="16">
            <el-form-item label="公告标题" prop="title">
              <el-input v-model="formData.title"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="公告类型" prop="type">
              <el-select v-model="formData.type" placeholder="请选择公告类型" style="width: 100%">
                <el-option label="系统公告" :value="1"></el-option>
                <el-option label="活动公告" :value="2"></el-option>
                <el-option label="维护公告" :value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="是否置顶" prop="isTop">
          <el-radio-group v-model="formData.isTop">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="公告内容" prop="content">
          <el-input v-model="formData.content" type="textarea" rows="8"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看公告对话框 -->
    <el-dialog
      title="公告详情"
      :visible.sync="viewDialogVisible"
      width="700px"
    >
      <div class="notice-detail">
        <div class="notice-header">
          <h3>{{ viewData.title }}</h3>
          <div class="notice-meta">
            <el-tag :type="viewData.type === 1 ? 'primary' : (viewData.type === 2 ? 'success' : 'warning')">
              {{ viewData.type === 1 ? '系统公告' : (viewData.type === 2 ? '活动公告' : '维护公告') }}
            </el-tag>
            <span class="meta-item">发布人：{{ viewData.publisherName }}</span>
            <span class="meta-item">发布时间：{{ viewData.createdTime }}</span>
          </div>
        </div>
        <div class="notice-content">
          <p>{{ viewData.content }}</p>
        </div>
      </div>
    </el-dialog>

    <!-- 状态修改对话框 -->
    <el-dialog title="修改公告状态" :visible.sync="statusDialogVisible" width="400px">
      <el-form :model="statusForm" label-width="100px">
        <el-form-item label="公告标题">
          <span>{{ statusForm.title }}</span>
        </el-form-item>
        <el-form-item label="当前状态">
          <el-tag :type="statusForm.status === 1 ? 'success' : 'danger'">
            {{ statusForm.status === 1 ? '发布' : '下线' }}
          </el-tag>
        </el-form-item>
        <el-form-item label="新状态">
          <el-radio-group v-model="statusForm.newStatus">
            <el-radio :label="1">发布</el-radio>
            <el-radio :label="3">下线</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="statusDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmStatusChange">确认修改</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog title="确认删除" :visible.sync="deleteDialogVisible" width="300px">
      <template #content>
        <p>确定要删除公告 {{ deleteNoticeTitle }} 吗？</p>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="handleConfirmDelete">确认删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { queryNotices, saveNotice, updateNotice, deleteNotice, updateNoticeStatus, updateNoticeTop } from "@/api/notice";

export default {
  data() {
    return {
      // 公告数据
      notices: [],

      // 搜索筛选
      title: "",
      status: "",

      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,

      // 对话框
      dialogVisible: false,
      dialogType: "add", // 'add' 或 'edit'
      dialogTitle: "发布公告",
      formData: {
        title: "", // 公告标题
        type: 1, // 公告类型
        content: "", // 公告内容
        isTop: 0 // 是否置顶
      },

      // 表单验证规则
      rules: {
        title: [{ required: true, message: "请输入公告标题", trigger: "blur" }],
        type: [{ required: true, message: "请选择公告类型", trigger: "change" }],
        content: [{ required: true, message: "请输入公告内容", trigger: "blur" }]
      },

      // 查看公告
      viewDialogVisible: false,
      viewData: {},

      // 状态修改相关
      statusDialogVisible: false,
      statusForm: {
        noticeId: "",
        title: "",
        status: 1,
        newStatus: 1
      },

      // 删除相关
      deleteDialogVisible: false,
      deleteNoticeId: "",
      deleteNoticeTitle: ""
    };
  },

  methods: {
    // 分页
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.handleSearch();
    },

    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.handleSearch();
    },

    // 搜索
    handleSearch() {
      const params = {
        title: this.title,
        status: this.status,
        pageSize: this.pageSize,
        page: this.currentPage
      };

      // 调用实际的API
      queryNotices(params).then(res => {
        if (res.data.code === 1) {
          const data = res.data.data;
          this.notices = data.records || [];
          this.total = data.total || 0;
        } else {
          this.$message.error(res.data.msg || "查询失败");
          // 如果API失败，使用模拟数据
          this.notices = [
            {
              noticeId: 1,
              title: "健身房开业通知",
              content: "欢迎大家来到我们的健身房！我们提供专业的健身设备和优质的服务。",
              type: 1,
              publisherId: "admin-001",
              publisherName: "系统管理员",
              status: 1,
              isTop: 1,
              createdTime: "2025-06-01 10:00:00",
              updatedTime: "2025-06-01 10:00:00"
            },
            {
              noticeId: 2,
              title: "春季健身活动",
              content: "春季健身活动即将开始，参与活动可获得精美礼品！",
              type: 2,
              publisherId: "admin-001",
              publisherName: "系统管理员",
              status: 1,
              isTop: 0,
              createdTime: "2025-06-02 14:30:00",
              updatedTime: "2025-06-02 14:30:00"
            },
            {
              noticeId: 3,
              title: "设备维护通知",
              content: "本周末将对部分设备进行维护，请大家合理安排健身时间。",
              type: 3,
              publisherId: "admin-001",
              publisherName: "系统管理员",
              status: 1,
              isTop: 0,
              createdTime: "2025-06-03 09:00:00",
              updatedTime: "2025-06-03 09:00:00"
            }
          ];
          this.total = 3;
        }
      }).catch(error => {
        console.error("查询公告失败:", error);
        this.$message.error("网络错误，查询失败");
        // 网络错误时使用模拟数据
        this.notices = [
          {
            noticeId: 1,
            title: "健身房开业通知",
            content: "欢迎大家来到我们的健身房！我们提供专业的健身设备和优质的服务。",
            type: 1,
            publisherId: "admin-001",
            publisherName: "系统管理员",
            status: 1,
            isTop: 1,
            createdTime: "2025-06-01 10:00:00",
            updatedTime: "2025-06-01 10:00:00"
          }
        ];
        this.total = 1;
      });
    },

    // 添加公告
    handleAdd() {
      this.dialogType = "add";
      this.dialogTitle = "发布公告";
      this.formData = {
        title: "",
        type: 1,
        content: "",
        isTop: 0
      };
      this.dialogVisible = true;
    },

    // 编辑公告
    handleEdit(row) {
      this.dialogType = "edit";
      this.dialogTitle = "编辑公告";
      this.formData = { ...row };
      this.dialogVisible = true;
    },

    // 查看公告
    handleView(row) {
      this.viewData = { ...row };
      this.viewDialogVisible = true;
    },

    // 保存公告信息
    handleSave() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          const data = { ...this.formData, status: 1 }; // 状态设为发布
          if (this.dialogType === "add") {
            // 添加新公告
            console.log("发布公告:", data);
            saveNotice(data).then(res => {
              if (res.data.code === 1) {
                this.$message.success("发布成功");
                this.dialogVisible = false;
                this.handleSearch();
              } else {
                this.$message.error(res.data.msg || "发布失败");
              }
            }).catch(error => {
              console.error("发布公告失败:", error);
              this.$message.error("网络错误，发布失败");
            });
          } else {
            // 编辑公告
            console.log("编辑公告:", data);
            updateNotice(data).then(res => {
              if (res.data.code === 1) {
                this.$message.success("修改成功");
                this.dialogVisible = false;
                this.handleSearch();
              } else {
                this.$message.error(res.data.msg || "修改失败");
              }
            }).catch(error => {
              console.error("编辑公告失败:", error);
              this.$message.error("网络错误，修改失败");
            });
          }
        } else {
          this.$message.error("请完善表单信息");
          return false;
        }
      });
    },

    // 关闭对话框
    handleClose(done) {
      this.$refs.formRef.resetFields();
      done();
    },

    // 置顶/取消置顶
    handleTopChange(row) {
      const newTopStatus = row.isTop === 1 ? 0 : 1;
      const action = newTopStatus === 1 ? "置顶" : "取消置顶";

      this.$confirm(`确定要${action}公告 "${row.title}" 吗？`, "确认操作", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        console.log(`${action}公告:`, row.noticeId, newTopStatus);
        updateNoticeTop(row.noticeId, newTopStatus).then(res => {
          if (res.data.code === 1) {
            this.$message.success(`${action}成功`);
            this.handleSearch();
          } else {
            this.$message.error(res.data.msg || `${action}失败`);
          }
        }).catch(error => {
          console.error(`${action}公告失败:`, error);
          this.$message.error(`网络错误，${action}失败`);
        });
      });
    },

    // 修改公告状态
    handleStatusChange(row) {
      this.statusForm = {
        noticeId: row.noticeId,
        title: row.title,
        status: row.status,
        newStatus: row.status
      };
      this.statusDialogVisible = true;
    },

    // 确认状态修改
    handleConfirmStatusChange() {
      if (this.statusForm.status === this.statusForm.newStatus) {
        this.$message.warning("状态未发生变化");
        return;
      }

      console.log("修改公告状态:", this.statusForm);
      updateNoticeStatus(this.statusForm.noticeId, this.statusForm.newStatus).then(res => {
        if (res.data.code === 1) {
          this.$message.success("状态修改成功");
          this.statusDialogVisible = false;
          this.handleSearch();
        } else {
          this.$message.error(res.data.msg || "状态修改失败");
        }
      }).catch(error => {
        console.error("修改公告状态失败:", error);
        this.$message.error("网络错误，状态修改失败");
      });
    },

    // 删除公告
    handleDelete(row) {
      this.deleteNoticeId = row.noticeId;
      this.deleteNoticeTitle = row.title;
      this.deleteDialogVisible = true;
    },

    // 确认删除
    handleConfirmDelete() {
      console.log("删除公告:", this.deleteNoticeId);
      deleteNotice(this.deleteNoticeId).then(res => {
        if (res.data.code === 1) {
          this.$message.success("删除成功");
          this.deleteDialogVisible = false;
          this.handleSearch();
        } else {
          this.$message.error(res.data.msg || "删除失败");
        }
      }).catch(error => {
        console.error("删除公告失败:", error);
        this.$message.error("网络错误，删除失败");
      });
    }
  },

  mounted() {
    this.handleSearch();
  }
};
</script>

<style lang="less" scoped>
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.filter-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  margin-bottom: 10px;

  .search-container {
    display: flex;

    .search-item {
      margin-right: 10px;

      .search-title {
        line-height: 32px;
        padding: 0 12px 0 0;
        color: #606266;
        font-size: 14px;
        font-weight: 700;
      }
    }
  }
}

.addDialog /deep/ .el-input {
  width: 100%;
}

.notice-detail {
  .notice-header {
    margin-bottom: 20px;

    h3 {
      margin: 0 0 10px 0;
      color: #303133;
      font-size: 18px;
    }

    .notice-meta {
      display: flex;
      align-items: center;
      color: #909399;
      font-size: 14px;

      .meta-item {
        margin-left: 15px;
      }
    }
  }

  .notice-content {
    padding: 20px;
    background-color: #f8f9fa;
    border-radius: 4px;
    line-height: 1.6;

    p {
      margin: 0;
      color: #606266;
    }
  }
}
</style>